package org.mall.modules.system.controller;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.shiro.SecurityUtils;
import org.mall.common.api.vo.LoginInfo;
import org.mall.common.api.vo.Result;
import org.mall.common.api.vo.UserInfo;
import org.mall.common.aspect.annotation.IPLimit;
import org.mall.common.constant.AppMessageTypeEnum;
import org.mall.common.constant.CommonConstant;
import org.mall.common.constant.ErrorCode;
import org.mall.common.system.api.ISysBaseAPI;
import org.mall.common.system.util.JwtUtil;
import org.mall.common.system.vo.LoginUser;
import org.mall.common.util.*;
import org.mall.common.util.encryption.EncryptedString;
import org.mall.common.util.json.JacksonUtils;
import org.mall.modules.member.entity.Member;
import org.mall.modules.member.service.IMemberService;
import org.mall.modules.message.service.AppMessageService;
import org.mall.modules.pojo.common.AppMessageDTO;
import org.mall.modules.seller.entity.Seller;
import org.mall.modules.seller.service.ISellerService;
import org.mall.modules.shiro.vo.DefContants;
import org.mall.modules.system.client.SmsClient;
import org.mall.modules.system.entity.SysDepart;
import org.mall.modules.system.entity.SysUser;
import org.mall.modules.system.model.SysLoginModel;
import org.mall.modules.system.model.VerificationCode;
import org.mall.modules.system.service.ISysDepartService;
import org.mall.modules.system.service.ISysLogService;
import org.mall.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author scott
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/sys")
@Api(tags="用户登录")
@Slf4j
public class LoginController {
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private ISysLogService logService;
	@Autowired
    private RedisUtil redisUtil;
	@Autowired
    private ISysDepartService sysDepartService;

	@Autowired

	private ISellerService sellerService;
	@Autowired
	private DefaultMQProducer defaultMQProducer;

	@Autowired
	private SmsClient smsClient;

	@Autowired
	private IMemberService memberService;

	@Autowired
	AppMessageService appMessageService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ApiOperation("登录接口")
	public Result<JSONObject> login(@RequestBody SysLoginModel sysLoginModel) throws Exception {
		Result<JSONObject> result = new Result<JSONObject>();
		String username = sysLoginModel.getUsername();
		String password = sysLoginModel.getPassword();
		//update-begin--Author:scott  Date:20190805 for：暂时注释掉密码加密逻辑，有点问题
		//前端密码加密，后端进行密码解密
		//password = AesEncryptUtil.desEncrypt(sysLoginModel.getPassword().replaceAll("%2B", "\\+")).trim();//密码解密
		//update-begin--Author:scott  Date:20190805 for：暂时注释掉密码加密逻辑，有点问题

		//1. 校验用户是否有效
		SysUser sysUser = sysUserService.getUserByName(username);
		result = sysUserService.checkUserIsEffective(sysUser);
		if(!result.isSuccess()) {
			return result;
		}
		
		//2. 校验用户名或密码是否正确
		String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
		String syspassword = sysUser.getPassword();
		if (!syspassword.equals(userpassword)) {
			result.error500("用户名或密码错误");
			return result;
		}
				
		//用户登录信息
		userInfo(sysUser, result);
		sysBaseAPI.addLog("用户名: " + username + ",登录成功！", CommonConstant.LOG_TYPE_1, null);

		return result;
	}
	
	/**
	 * 退出登录
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/logout")
	public Result<Object> logout(HttpServletRequest request,HttpServletResponse response) {
		//用户退出逻辑
	    String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
	    if(oConvertUtils.isEmpty(token)) {
	    	return Result.error("退出登录失败！");
	    }
	    String username = JwtUtil.getUsername(token);
	    SysUser sysUser = sysUserService.getUserByName(username);
	    if(sysUser!=null) {
	    	sysBaseAPI.addLog("用户名: "+sysUser.getRealname()+",退出成功！", CommonConstant.LOG_TYPE_1, null);
	    	log.info(" 用户名:  "+sysUser.getRealname()+",退出成功！ ");
	    	//清空用户Token缓存
	    	redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
	    	//清空用户权限缓存：权限Perms和角色集合
	    	redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_ROLE + username);
	    	redisUtil.del(CommonConstant.LOGIN_USER_CACHERULES_PERMISSION + username);
	    	return Result.ok("退出登录成功！");
	    }else {
	    	return Result.error("无效的token");
	    }
	}
	@RequestMapping(value = "/app/member/logout")
	public Result<Object> memberLogout(HttpServletRequest request,HttpServletResponse response) {
		//用户退出逻辑
		String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
		if(oConvertUtils.isEmpty(token)) {
			return Result.error("退出登录失败！");
		}
		String username = JwtUtil.getUsername(token);
		String userId = JwtUtil.getUserIdByToken();
		Member member = memberService.getOneByName(userId, username);
		if(member!=null) {
			sysBaseAPI.addLog("用户名: "+member.getUsername()+",退出成功！", CommonConstant.LOG_TYPE_1, null);
			log.info(" 用户名:  "+member.getUsername()+",退出成功！ ");
			//清空用户Token缓存
			redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
			//清空用户权限缓存：权限Perms和角色集合
			return Result.ok("退出登录成功！");
		}else {
			return Result.error("无效的token");
		}
	}
	@RequestMapping(value = "/merchant/seller/logout")
	public Result<Object> sellerLogout(HttpServletRequest request,HttpServletResponse response) {
		//用户退出逻辑
		String token = request.getHeader(DefContants.X_ACCESS_TOKEN);
		if(oConvertUtils.isEmpty(token)) {
			return Result.error("退出登录失败！");
		}
		String username = JwtUtil.getUsername(token);
		Seller seller = sellerService.getOneByMobile(username);
		if(seller!=null) {
			sysBaseAPI.addLog("用户名: "+seller.getUsername()+",退出成功！", CommonConstant.LOG_TYPE_1, null);
			log.info(" 用户名:  "+seller.getUsername()+",退出成功！ ");
			//清空用户Token缓存
			redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + token);
			return Result.ok("退出登录成功！");
		}else {
			return Result.error("无效的token");
		}
	}
	
	/**
	 * 获取访问量
	 * @return
	 */
	@GetMapping("loginfo")
	public Result<JSONObject> loginfo() {
		Result<JSONObject> result = new Result<JSONObject>();
		JSONObject obj = new JSONObject();
		//update-begin--Author:zhangweijian  Date:20190428 for：传入开始时间，结束时间参数
		// 获取一天的开始和结束时间
		Calendar calendar = new GregorianCalendar();
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		Date dayStart = calendar.getTime();
		calendar.add(Calendar.DATE, 1);
		Date dayEnd = calendar.getTime();
		// 获取系统访问记录
		Long totalVisitCount = logService.findTotalVisitCount();
		obj.put("totalVisitCount", totalVisitCount);
		Long todayVisitCount = logService.findTodayVisitCount(dayStart,dayEnd);
		obj.put("todayVisitCount", todayVisitCount);
		Long todayIp = logService.findTodayIp(dayStart,dayEnd);
		//update-end--Author:zhangweijian  Date:20190428 for：传入开始时间，结束时间参数
		obj.put("todayIp", todayIp);
		result.setResult(obj);
		result.success("登录成功");
		return result;
	}
	
	/**
	 * 获取访问量
	 * @return
	 */
	@GetMapping("visitInfo")
	public Result<List<Map<String,Object>>> visitInfo() {
		Result<List<Map<String,Object>>> result = new Result<List<Map<String,Object>>>();
		Calendar calendar = new GregorianCalendar();
		calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        Date dayEnd = calendar.getTime();
        calendar.add(Calendar.DAY_OF_MONTH, -7);
        Date dayStart = calendar.getTime();
        List<Map<String,Object>> list = logService.findVisitCount(dayStart, dayEnd);
		result.setResult(oConvertUtils.toLowerCasePageList(list));
		return result;
	}
	
	
	/**
	 * 登陆成功选择用户当前部门
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/selectDepart", method = RequestMethod.PUT)
	public Result<JSONObject> selectDepart(@RequestBody SysUser user) {
		Result<JSONObject> result = new Result<JSONObject>();
		String username = user.getUsername();
		if(oConvertUtils.isEmpty(username)) {
			LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
			username = sysUser.getUsername();
		}
		String orgCode= user.getOrgCode();
		this.sysUserService.updateUserDepart(username, orgCode);
		SysUser sysUser = sysUserService.getUserByName(username);
		JSONObject obj = new JSONObject();
		obj.put("userInfo", sysUser);
		result.setResult(obj);
		return result;
	}

	/**
	 * 短信登录接口
	 * 
	 * @param jsonObject
	 * @return
	 */
	@PostMapping(value = "/sms")
	public Result<String> sms(@RequestBody JSONObject jsonObject) {
		Result<String> result = new Result<String>();
		String mobile = jsonObject.get("mobile").toString();
		String smsmode=jsonObject.get("smsmode").toString();
		log.info(mobile);	
		Object object = redisUtil.get(mobile);
		if (object != null) {
			result.setMessage("验证码10分钟内，仍然有效！");
			result.setSuccess(false);
			return result;
		}

		//随机数
		String captcha = RandomUtil.randomNumbers(6);
		JSONObject obj = new JSONObject();
    	obj.put("code", captcha);
		try {
			boolean b = false;
			//注册模板
			if (CommonConstant.SMS_TPL_TYPE_1.equals(smsmode)) {
				SysUser sysUser = sysUserService.getUserByPhone(mobile);
				if(sysUser!=null) {
					result.error500(" 手机号已经注册，请直接登录！");
					sysBaseAPI.addLog("手机号已经注册，请直接登录！", CommonConstant.LOG_TYPE_1, null);
					return result;
				}
				b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.REGISTER_TEMPLATE_CODE);
			}else {
				//登录模式，校验用户有效性
				SysUser sysUser = sysUserService.getUserByPhone(mobile);
				result = sysUserService.checkUserIsEffective(sysUser);
				if(!result.isSuccess()) {
					return result;
				}
				
				/**
				 * smsmode 短信模板方式  0 .登录模板、1.注册模板、2.忘记密码模板
				 */
				if (CommonConstant.SMS_TPL_TYPE_0.equals(smsmode)) {
					//登录模板
					b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.LOGIN_TEMPLATE_CODE);
				} else if(CommonConstant.SMS_TPL_TYPE_2.equals(smsmode)) {
					//忘记密码模板
					b = DySmsHelper.sendSms(mobile, obj, DySmsEnum.FORGET_PASSWORD_TEMPLATE_CODE);
				}
			}

			if (b == false) {
				result.setMessage("短信验证码发送失败,请稍后重试");
				result.setSuccess(false);
				return result;
			}
			//验证码10分钟内有效
			redisUtil.set(mobile, captcha, 600);
			//update-begin--Author:scott  Date:20190812 for：issues#391
			//result.setResult(captcha);
			//update-end--Author:scott  Date:20190812 for：issues#391
			result.setSuccess(true);

		} catch (ClientException e) {
			e.printStackTrace();
			result.error500(" 短信接口未配置，请联系管理员！");
			return result;
		}
		return result;
	}
	

	/**
	 * 手机号登录接口
	 * 
	 * @param jsonObject
	 * @return
	 */
	@PostMapping("/phoneLogin")
	public Result<JSONObject> phoneLogin(@RequestBody JSONObject jsonObject) {
		Result<JSONObject> result = new Result<JSONObject>();
		String phone = jsonObject.getString("mobile");
		
		//校验用户有效性
		SysUser sysUser = sysUserService.getUserByPhone(phone);
		result = sysUserService.checkUserIsEffective(sysUser);
		if(!result.isSuccess()) {
			return result;
		}
		
		String smscode = jsonObject.getString("captcha");
		Object code = redisUtil.get(phone);
		if (!smscode.equals(code)) {
			result.setMessage("手机验证码错误");
			return result;
		}
		//用户信息
		userInfo(sysUser, result);
		//添加日志
		sysBaseAPI.addLog("用户名: " + sysUser.getUsername() + ",登录成功！", CommonConstant.LOG_TYPE_1, null);

		return result;
	}


	/**
	 * 用户信息
	 *
	 * @param sysUser
	 * @param result
	 * @return
	 */
	private Result<JSONObject> userInfo(SysUser sysUser, Result<JSONObject> result) {
		String syspassword = sysUser.getPassword();
		String username = sysUser.getUsername();
		// 生成token
		String token = JwtUtil.sign(username, syspassword,sysUser.getId());
		redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
		// 设置超时时间
		redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);

		// 获取用户部门信息
		JSONObject obj = new JSONObject();
		List<SysDepart> departs = sysDepartService.queryUserDeparts(sysUser.getId());
		obj.put("departs", departs);
		if (departs == null || departs.size() == 0) {
			obj.put("multi_depart", 0);
		} else if (departs.size() == 1) {
			sysUserService.updateUserDepart(username, departs.get(0).getOrgCode());
			obj.put("multi_depart", 1);
		} else {
			obj.put("multi_depart", 2);
		}
		obj.put("token", token);
		obj.put("userInfo", sysUser);
		result.setResult(obj);
		result.success("登录成功");
		return result;
	}
	private Result<JSONObject> memberInfo(Member sysUser, Result<JSONObject> result) {
		// 生成token
		UserInfo userInfo=new UserInfo();
		userInfo.setUserName(sysUser.getUsername());
		userInfo.setMobile(sysUser.getMobile());
		userInfo.setUserId(sysUser.getId());
		userInfo.setType(sysUser.getType());
		String token = JwtUtil.sign(userInfo);
		redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
		// 设置超时时间
		redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);

		// 获取用户部门信息
		JSONObject obj = new JSONObject();
		obj.put("access_token", token);
		obj.put("userInfno",sysUser);
		result.setResult(obj);
		result.success("登录成功");
		return result;
	}
	/**
	 * 获取加密字符串
	 * @return
	 */
	@GetMapping(value = "/getEncryptedString")
	public Result<Map<String,String>> getEncryptedString(){
		Result<Map<String,String>> result = new Result<Map<String,String>>();
		Map<String,String> map = new HashMap<String,String>();
		map.put("key", EncryptedString.key);
		map.put("iv",EncryptedString.iv);
		result.setResult(map);
		return result;
	}
	@PostMapping("/app/member/loginByMobile")
	public Result<?> memberLogin(@RequestBody LoginInfo loginInfo){
		Result result=new Result();
		result.setSuccess(false);
		if (StringUtils.isEmpty(loginInfo.getMobile())||StringUtils.isEmpty(loginInfo.getCode())){
			result.setMessage(ErrorCode.LOGIN_ERROR_INFO);
			return result;
		}

//		Object o=redisUtil.getMemberCode(loginInfo.getMobile());
//		if (o==null){
//			result.setMessage(ErrorCode.LOGIN_CODE_TIMEOUT);
//			return result;
//		}
//		if (! loginInfo.getCode().equals(o)){
//			result.setMessage(ErrorCode.LOGIN_ERROR_PASSWOD);
//			return result;
//		}

		Member member=memberService.getByMobile(loginInfo.getMobile());
		if (member==null){
			member=new Member();
			member.setMobile(loginInfo.getMobile());
			member.setUsername(loginInfo.getMobile());
			member.setState(0);
			member.setIsDelete(0);
			member.setCreateTime(new Date());
			member.setNickName(RandomUtil.randomString(5));
			member.setId(UUIDGenerator.generate());
			memberService.save(member);

			AppMessageDTO appMessageDTO = new AppMessageDTO();
			appMessageDTO.setTitle("然气惠民");
			appMessageDTO.setContent("恭喜您，注册成功！");
			appMessageDTO.setCreateTime(DateUtils.getDate());
			appMessageDTO.setCreator("");
			appMessageDTO.setReceiver(member.getId());
			appMessageDTO.setTemplateId(1);
			appMessageDTO.setType(AppMessageTypeEnum.MEMBER_NOTIFICATION.getValue());
			appMessageService.sendAppMessageToUser(appMessageDTO);

		}
		if (member.getState()==1){
			return Result.error("账户被冻结");
		}
		if (member.getIsDelete()==1){
			return Result.error("账户被锁定");
		}
		sysBaseAPI.addLog("用户名: " + member.getUsername() + ",登录成功！", CommonConstant.LOG_TYPE_1, null);
		redisUtil.delMemberCode(loginInfo.getMobile());
		member.setPassword(loginInfo.getMobile());
		return memberInfo(member, result);

	}
	@IPLimit(count = 1)
	@GetMapping("/app/member/getVerificationCode")
	public Result getVerificationCodeOfMember(@RequestParam  String mobile){
		Result result=new Result();
		result.setSuccess(false);
		String code=RandomUtil.randomNumbers(4);
		for (;;){

			if (!code.startsWith("0")){
				break;
			}
			code=RandomUtil.randomNumbers(4);

		}
		redisUtil.setMemberCode(mobile,code,600);
		if (StringUtils.isEmpty(mobile)){
			result.setMessage("手机号不能为空");
			return result;
		}
		VerificationCode verificationCode=new VerificationCode();
		verificationCode.setCode(code);
		redisUtil.setMemberCode(mobile,code,3000);
		defaultMQProducer.setProducerGroup("mall-group");
		smsClient.singleSendVerificationCode(mobile,code);

		return Result.ok(verificationCode);
	}
	@GetMapping("/merchant/seller/getVerificationCode")
	public Result getVerificationCodeOfSeller(@RequestParam  String mobile){
		Result result=new Result();
		result.setSuccess(false);
		String code=RandomUtil.randomNumbers(4);
		for (;;){

			if (!code.startsWith("0")){
				break;
			}
			code=RandomUtil.randomNumbers(4);

		}
		VerificationCode verificationCode=new VerificationCode();
		verificationCode.setCode(code);
		redisUtil.setSellerCode(mobile,code,600);
		if (StringUtils.isEmpty(mobile)){
			result.setMessage("手机号不能为空");
			return result;
		}
		redisUtil.setSellerCode(mobile,code,3000);
		smsClient.singleSendVerificationCode(mobile,code);

		return Result.ok(verificationCode);
	}

	@PostMapping("/merchant/seller/loginByMobile")
	public Result<?> sellerLogin(@RequestBody LoginInfo loginInfo){
		Result result=new Result();
		result.setSuccess(false);
		if (StringUtils.isEmpty(loginInfo.getMobile())||StringUtils.isEmpty(loginInfo.getCode())){
			result.setMessage(ErrorCode.LOGIN_ERROR_INFO);
			result.setCode(500);
			return result;
		}

		Object o=redisUtil.getSellerCode(loginInfo.getMobile());
		if (o==null){
			result.setMessage(ErrorCode.LOGIN_CODE_TIMEOUT);
			result.setCode(500);
			return result;
		}
		if (! loginInfo.getCode().equals(o)){
			result.setMessage(ErrorCode.LOGIN_ERROR_PASSWOD);
			result.setCode(500);
			return result;
		}

		Seller seller=sellerService.getOneByMobile(loginInfo.getMobile());
		if (seller==null||seller.getState()==1||seller.getIsDelete()==1){
			return Result.error("用户不存在，请联系管理员");
		}
		sysBaseAPI.addLog("用户名: " + seller.getUsername() + ",登录成功！", CommonConstant.LOG_TYPE_1, null);
		redisUtil.delMemberCode(loginInfo.getMobile());
		seller.setUsername(loginInfo.getMobile());
		seller.setPassword(loginInfo.getMobile());
		return sellerInfo(seller, result);

	}

	private Result<?> sellerInfo(Seller seller, Result result) {

		UserInfo userInfo=new UserInfo();
		userInfo.setUserName(seller.getUsername());
		userInfo.setMobile(seller.getMobile());
		userInfo.setUserId(seller.getId());
		userInfo.setType(seller.getType());
		// 生成token
		String token = JwtUtil.sign(userInfo);
		redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
		// 设置超时时间
		redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);

		// 获取用户部门信息
		JSONObject obj = new JSONObject();
		obj.put("access_token", token);
		obj.put("userInfo",seller);
		result.setResult(obj);
		result.success("登录成功");
		return result;
	}
}